<template>
  <div class="whisper-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <div class="header-title">
            <h1>悄悄话</h1>
            <p>发送私密消息，分享你的心声</p>
          </div>
        </div>
      </div>
    </div>

    <div class="page-content">
      <div class="main-content">
        <!-- 悄悄话搜索功能 -->
        <el-card class="search-whispers-card">
          <template #header>
            <div class="card-header">
              <span>搜索悄悄话</span>
            </div>
          </template>

          <div class="search-section">
            <el-form
              :model="searchForm"
              :inline="true"
              @submit.prevent="handleSearch"
              class="search-form"
            >
              <el-form-item>
                <el-select
                  v-model="searchForm.searchType"
                  placeholder="选择搜索类型"
                  style="width: 140px"
                >
                  <el-option label="全部" value="all" />
                  <el-option label="用户名" value="username" />
                  <el-option label="暗号" value="code" />
                </el-select>
              </el-form-item>

              <el-form-item class="search-input-item">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="输入关键词进行搜索"
                  clearable
                  @keyup.enter="handleSearch"
                  class="search-input"
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="handleSearch" :loading="searchLoading"
                  >搜索</el-button
                >
              </el-form-item>
            </el-form>

            <!-- 搜索结果 -->
            <div class="search-results" v-if="searchResults.length > 0 || hasSearched">
              <div class="results-header">
                <div class="results-title">
                  <h4>搜索结果</h4>
                  <el-tag type="info" size="large">找到 {{ searchTotal }} 条悄悄话</el-tag>
                </div>
                <el-button
                  @click="toggleSearchResults"
                  :icon="searchResultsCollapsed ? ArrowDown : ArrowUp"
                  circle
                  size="small"
                  type="info"
                  plain
                  :title="searchResultsCollapsed ? '展开搜索结果' : '折叠搜索结果'"
                />
              </div>

              <div class="whisper-list" v-loading="searchLoading" v-show="!searchResultsCollapsed">
                <div v-if="searchResults.length === 0" class="empty-state">
                  <el-empty description="没有找到相关的悄悄话" />
                </div>

                <div v-for="whisper in searchResults" :key="whisper.id" class="whisper-item">
                  <div class="whisper-card">
                    <div class="whisper-header">
                      <div class="sender-info">
                        <el-avatar :size="40" class="sender-avatar">
                          {{ whisper.isAnonymous ? "匿" : whisper.senderName?.charAt(0) || "?" }}
                        </el-avatar>
                        <div class="sender-detail">
                          <span class="sender-name">
                            {{ whisper.isAnonymous ? "匿名用户" : whisper.senderName }}
                          </span>
                          <div class="target-info">
                            <el-icon><ArrowRight /></el-icon>
                            <span>{{
                              whisper.recipientType === "username" ? "用户: " : "暗号: "
                            }}</span>
                            <span class="target-value">{{ whisper.recipientValue }}</span>
                          </div>
                        </div>
                      </div>
                      <div class="whisper-time">
                        {{ formatTime(whisper.createdAt) }}
                      </div>
                    </div>

                    <div class="whisper-content">
                      {{ whisper.content }}
                    </div>

                    <div class="whisper-footer">
                      <div class="whisper-tags">
                        <el-tag
                          size="small"
                          :type="whisper.recipientType === 'username' ? 'primary' : 'success'"
                          effect="light"
                        >
                          {{ whisper.recipientType === "username" ? "定向消息" : "暗号消息" }}
                        </el-tag>
                        <el-tag
                          size="small"
                          :type="whisper.isAnonymous ? 'warning' : 'info'"
                          effect="light"
                        >
                          {{ whisper.isAnonymous ? "匿名" : "实名" }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 分页 -->
                <div class="pagination-wrapper" v-if="searchTotal > 10">
                  <el-pagination
                    v-model:current-page="searchForm.page"
                    :page-size="searchForm.size"
                    :total="searchTotal"
                    layout="total, prev, pager, next"
                    @current-change="handleSearchPageChange"
                  />
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 发送悄悄话区域 -->
        <el-card class="whisper-form-card">
          <template #header>
            <div class="card-header">
              <span>发送悄悄话</span>
            </div>
          </template>

          <el-form
            :model="whisperForm"
            :rules="whisperRules"
            ref="whisperFormRef"
            label-position="top"
            class="whisper-form"
          >
            <!-- 发送类型选择 -->
            <el-form-item label="发送方式" prop="targetType">
              <el-radio-group v-model="whisperForm.targetType" class="send-type-group">
                <el-radio-button :label="1">指定用户</el-radio-button>
                <el-radio-button :label="2">暗号接收</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <!-- 接收者输入 -->
            <el-form-item
              :label="whisperForm.targetType === 1 ? '接收用户' : '接收暗号'"
              prop="targetValue"
            >
              <el-input
                v-model="whisperForm.targetValue"
                :placeholder="
                  whisperForm.targetType === 1 ? '请输入接收者用户名' : '请输入接收暗号'
                "
                clearable
                class="target-input"
              />
            </el-form-item>

            <!-- 消息内容 -->
            <el-form-item label="消息内容" prop="content">
              <el-input
                v-model="whisperForm.content"
                type="textarea"
                :rows="6"
                placeholder="请输入你想说的话..."
                maxlength="500"
                show-word-limit
                resize="none"
                class="content-textarea"
              />
            </el-form-item>

            <!-- 发送设置 -->
            <el-form-item label="发送设置">
              <el-radio-group v-model="whisperForm.isAnonymous" class="anonymous-group">
                <el-radio-button :label="true">匿名发送</el-radio-button>
                <el-radio-button :label="false" v-if="isAuth">实名发送</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <!-- 匿名昵称 -->
            <el-form-item
              label="匿名昵称（可选）"
              prop="senderNickname"
              v-if="whisperForm.isAnonymous"
            >
              <el-input
                v-model="whisperForm.senderNickname"
                placeholder="请输入临时昵称"
                clearable
              />
            </el-form-item>

            <!-- 操作按钮 -->
            <el-form-item>
              <div class="form-actions">
                <el-button @click="resetForm">重置</el-button>
                <el-button type="primary" @click="sendWhisper" :loading="sending"
                  >发送悄悄话</el-button
                >
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { ArrowRight, ArrowDown, ArrowUp } from "@element-plus/icons-vue";
import { isAuthenticated } from "@/utils/auth";
import {
  sendWhisper as sendWhisperApi,
  searchWhispers,
  type WhisperCreateRequest,
  type WhisperDTO,
} from "@/api/whisper";

// 响应式数据
const sending = ref(false);
const whisperFormRef = ref<FormInstance>();
const searchLoading = ref(false);
const hasSearched = ref(false);
const searchTotal = ref(0);
const searchResultsCollapsed = ref(false);

const publicWhispers = ref<WhisperDTO[]>([]);
const searchResults = ref<WhisperDTO[]>([]);

// 表单数据
const whisperForm = reactive({
  targetType: 1, // 1: 用户名, 2: 暗号
  targetValue: "",
  content: "",
  isAnonymous: true,
  senderNickname: "",
});

// 搜索表单数据
const searchForm = reactive({
  keyword: "",
  searchType: "all",
  page: 1,
  size: 10,
});

// 表单验证规则
const whisperRules = {
  targetValue: [{ required: true, message: "请输入接收者", trigger: "blur" }],
  content: [
    { required: true, message: "请输入悄悄话内容", trigger: "blur" },
    { min: 1, max: 500, message: "内容长度在 1 到 500 个字符", trigger: "blur" },
  ],
};

// 是否已登录
const isAuth = computed(() => isAuthenticated());

// 发送悄悄话
const sendWhisper = async () => {
  if (!whisperFormRef.value) return;

  try {
    await whisperFormRef.value.validate();

    sending.value = true;

    // 准备API数据
    const whisperData: WhisperCreateRequest = {
      recipientType: whisperForm.targetType === 1 ? "username" : "code",
      recipientValue: whisperForm.targetValue,
      content: whisperForm.content,
      isAnonymous: whisperForm.isAnonymous,
      senderName: whisperForm.isAnonymous ? whisperForm.senderNickname : undefined,
    };

    // 调用API发送悄悄话
    await sendWhisperApi(whisperData);

    ElMessage.success("悄悄话发送成功！");
    resetForm();
  } catch (error: any) {
    console.error("Send whisper error:", error);
    ElMessage.error(error.message || "发送失败，请重试");
  } finally {
    sending.value = false;
  }
};

// 重置表单
const resetForm = () => {
  if (whisperFormRef.value) {
    whisperFormRef.value.resetFields();
  }
  whisperForm.targetType = 1;
  whisperForm.targetValue = "";
  whisperForm.content = "";
  whisperForm.isAnonymous = true;
  whisperForm.senderNickname = "";
};

// 加载公开悄悄话（使用搜索API获取一些示例）
const loadPublicWhispers = async () => {
  try {
    // 暂时显示为空，可以根据需要实现
    publicWhispers.value = [];
  } catch (error) {
    console.error("Failed to load public whispers:", error);
  }
};

// 搜索悄悄话
const handleSearch = async () => {
  if (!searchForm.keyword.trim()) {
    ElMessage.warning("请输入搜索关键词");
    return;
  }

  searchLoading.value = true;
  hasSearched.value = true;

  try {
    const response = await searchWhispers({
      keyword: searchForm.keyword,
      searchType: searchForm.searchType as "all" | "username" | "code",
      page: searchForm.page,
      size: searchForm.size,
    });

    searchResults.value = response.items || [];
    searchTotal.value = response.total || 0;

    if (searchResults.value.length === 0) {
      ElMessage.info("没有找到相关的悄悄话");
    }
  } catch (error) {
    console.error("Search failed:", error);
    ElMessage.error("搜索失败，请重试");
  } finally {
    searchLoading.value = false;
  }
};

// 清空搜索
const clearSearch = () => {
  searchForm.keyword = "";
  searchForm.searchType = "all";
  searchForm.page = 1;
  searchResults.value = [];
  searchTotal.value = 0;
  hasSearched.value = false;
};

// 搜索分页
const handleSearchPageChange = (page: number) => {
  searchForm.page = page;
  handleSearch();
};

// 切换搜索结果展开/折叠
const toggleSearchResults = () => {
  searchResultsCollapsed.value = !searchResultsCollapsed.value;
};

// 格式化时间
const formatTime = (time: string) => {
  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (days === 0) {
    const hours = Math.floor(diff / (1000 * 60 * 60));
    if (hours === 0) {
      const minutes = Math.floor(diff / (1000 * 60));
      return minutes === 0 ? "刚刚" : `${minutes}分钟前`;
    }
    return `${hours}小时前`;
  } else if (days === 1) {
    return "昨天";
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return date.toLocaleDateString();
  }
};

// 组件挂载
onMounted(() => {
  loadPublicWhispers();
});
</script>

<style scoped lang="scss">
.whisper-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;

  .page-header {
    background-color: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    padding: 20px;

    .header-content {
      max-width: 1200px;
      margin: 0 auto;

      .header-left {
        .header-title {
          h1 {
            margin: 0 0 8px 0;
            font-size: 24px;
            color: #303133;
          }

          p {
            margin: 0;
            color: #909399;
            font-size: 14px;
          }
        }
      }
    }
  }

  .page-content {
    max-width: 1200px;
    margin: 0 auto;

    .main-content {
      display: flex;
      flex-direction: column;
      gap: 20px;

      .search-whispers-card,
      .whisper-form-card {
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        border-radius: 8px;

        .card-header {
          span {
            color: #303133;
            font-size: 16px;
            font-weight: 600;
          }
        }

        .whisper-form,
        .search-form {
          max-width: 600px;
          margin: 0 auto;
        }

        .form-actions {
          display: flex;
          gap: 12px;
          justify-content: flex-end;
          margin-top: 16px;
        }
      }

      .search-whispers-card {
        .search-section {
          .search-form {
            margin-bottom: 20px;
          }
        }

        .search-results {
          .results-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
            padding-bottom: 12px;
            border-bottom: 1px solid #ebeef5;

            .results-title {
              display: flex;
              align-items: center;
              gap: 12px;

              h4 {
                margin: 0;
                color: #303133;
                font-size: 16px;
                font-weight: 600;
              }
            }
          }

          .whisper-item {
            .whisper-card {
              background: #f8f9fa;
              border: 1px solid #ebeef5;
              border-radius: 8px;
              padding: 16px;
              margin-bottom: 12px;
              transition: all 0.2s;

              &:hover {
                border-color: #c6e2ff;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
              }

              .whisper-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 12px;

                .sender-info {
                  display: flex;
                  align-items: center;
                  gap: 12px;

                  .sender-detail {
                    display: flex;
                    flex-direction: column;

                    .sender-name {
                      font-weight: 500;
                      color: #303133;
                      margin-bottom: 4px;
                    }

                    .target-info {
                      display: flex;
                      align-items: center;
                      gap: 4px;
                      color: #909399;
                      font-size: 12px;

                      .target-value {
                        font-weight: 500;
                        color: #409eff;
                      }
                    }
                  }
                }

                .whisper-time {
                  font-size: 12px;
                  color: #909399;
                }
              }

              .whisper-content {
                color: #606266;
                line-height: 1.6;
                margin-bottom: 12px;
                background: #ffffff;
                padding: 12px;
                border-radius: 6px;
                border: 1px solid #ebeef5;
              }

              .whisper-footer {
                display: flex;
                justify-content: flex-end;
                gap: 8px;

                .whisper-tags {
                  display: flex;
                  gap: 8px;
                }
              }
            }
          }

          .pagination-wrapper {
            display: flex;
            justify-content: center;
            margin-top: 20px;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .whisper-page {
    padding: 10px;

    .page-content {
      .main-content {
        .search-whispers-card,
        .whisper-form-card {
          .whisper-form,
          .search-form {
            max-width: 100%;
          }
        }

        .search-whispers-card {
          .search-section {
            .search-form {
              flex-direction: column;
              align-items: stretch;

              .search-input-item {
                width: 100%;
              }
            }
          }
        }
      }
    }
  }
}
</style>
